<script lang="ts" setup>
import type { RealmForm } from '@/api/realm/types'
import * as realm from '@/api/realm'
import type { FormInstance, FormRules } from 'element-plus'

const props = reactive<FormDialogProp>({
    title: '',
    visible: false,
})

const open = async (id?: string) => {
    if(id === undefined) {
        props.title = '添加应用域'
    } else {
        formData.value = await realm.get(id)
        props.title = '编辑应用域'
    }

    props.visible = true
    props.id = id
}

defineExpose({
    open
})

const emit = defineEmits(['close'])

const formRef = ref<FormInstance>()
const defaultData = () => ({
    name: ''
})
const formData = ref<RealmForm>(defaultData())
const formRules = reactive<FormRules<RealmForm>>({
    name: [
        { required: true, message: '域名称不能为空', trigger: 'blur' }
    ]
})

const submit = async () => {
    await formRef.value?.validate(async (valid) => {
        if(valid) {
            let result: ApiResult
            if(props.id === undefined){
                result = await realm.add(formData.value)
            } else {
                result = await realm.edit(props.id, formData.value)
            }

            if(result.success) {
                ElMessage.success(result.message)
                props.visible = false
                emit('close')
            } else {
                ElMessage.error(result.message)
            }
        }
    })

    
}
</script>

<template>
    <el-dialog v-model="props.visible" :title="props.title">
        <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px">
            <el-form-item label="域名称" prop="name">
                <el-input v-model="formData.name"></el-input>
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button type="primary" @click="submit">确定</el-button>
        </template>
    </el-dialog>
</template>

<style lang="scss" scoped>

</style>